package com.sky.sms.core;

import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.sky.sms.properties.AliyunSmsProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

/**
 * 阿里云短信服务
 * @author zgp
 * @version V1.0
 * @date 2025-02-11 17:43
 */
@Slf4j
public class AliyunSmsTemplate {

    private AliyunSmsProperties aliyunSmsProperties;
    private AsyncClient asyncClient;

    public AliyunSmsTemplate(AliyunSmsProperties aliyunSmsProperties, AsyncClient asyncClient) {
        this.aliyunSmsProperties = aliyunSmsProperties;
        this.asyncClient = asyncClient;
    }

    /**
     * 发送短信
     * @param phoneNumber 手机号
     * @param templateParam 验证码
     */
    public void sendMessage(String phoneNumber, String templateParam){
        log.info("aliyunSmsProperties：{}", aliyunSmsProperties);
        try {
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(aliyunSmsProperties.getSignName())
                    .templateCode(aliyunSmsProperties.getTemplateCode())
                    .phoneNumbers(phoneNumber)
                    .templateParam("{\"code\":\""+ templateParam + "\"}")
                    .build();
            CompletableFuture<SendSmsResponse> response = asyncClient.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));

        } catch (Exception e) {
            log.error("短信发送异常：{}", e.getMessage(), e);
        } finally {
            if(asyncClient != null){
                // 关闭连接资源
                asyncClient.close();
            }
        }
    }
}
